<template>
  <el-container>
    <el-main>
        <div class="chat-container">
          <el-scrollbar  ref="scrollbar">
            <el-empty v-if="msgList.length == 0" description="没有记录" />
            <div v-else v-for="(item,index) in msgList" :key="index">
              <div v-if="item.type === 'bot'" class="bot-message">
                <img class="avatar" src="img/chatgpticon.svg" />
                <v-md-preview style="min-height:20px" :text="item.content"></v-md-preview>
              </div>
              <div v-if="item.type === 'user'" class="user-message">
                <img class="avatar" src="img/chat_avatar.svg" />
                <v-md-preview style="min-height:20px" :text="item.content"></v-md-preview>
              </div>
            </div>
        </el-scrollbar>
      </div>
      <div class="input-container">
        <input v-model="question" type="text" placeholder="输入内容..." @keyup.enter="buttonExe" />
        <el-button :disabled="buttonDisable" type="primary" size="large"  @click="buttonExe">{{buttonTitle}}</el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name:"xhChatGPT",
  data(){
    return{
      question:'',
      socket:null,
      msgList:[
        
      ],
      buttonDisable:false,
      buttonTitle:"发送",
      buttonType:"send",
      currentCompletionId:""
    }
  },
  methods:{
    createConnect(){
      let text = "";
      if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        this.socket = new WebSocket(`ws://${location.host}/gptws/xunheng-chatgpt/websocket/`+this.getCurrToken());
        //连接打开事件
        this.socket.onopen = function () {
            console.log("Socket 已打开");
            this.buttonDisable = false;
        };
        //收到消息事件
        this.socket.onmessage = (msg) => {
            //按扭文本变为停止
            this.buttonTitle = "停止";
            this.buttonDisable = false;  
            this.buttonType = "stop";
            if (msg.data == "[DONE]") {
                text = '';
                //按扭回归初始状态 按扭文本变为发送
                this.buttonTitle = "发送";
                this.buttonDisable = false;  
                this.buttonType = "send";
                //将当前的消息列表保存到本地存储
                this.$TOOL.data.set(this.getCurrUserId()+"chatgptMsgList",this.msgList);
                //清除正在生成的对话id
                this.currentCompletionId = null;
                return;
            }
            let json_data = JSON.parse(msg.data)
            if (json_data.content == null || json_data.content == 'null') {
                text = '';
                return;
            }
            this.currentCompletionId = json_data.completionId
            text = text + json_data.content;
            this.msgList[this.msgList.length -1].content = text;
            this.$refs.scrollbar.setScrollTop(10000);
            console.log(this.msgList[this.msgList.length -1].content);
        };
        //连接关闭事件
        this.socket.onclose = function () {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        this.socket.onerror = () => {
           this.$message.error("chatGPT服务未启动");
           this.buttonDisable = true;
        }  
      }
    },
    buttonExe(){
      if(this.buttonType === 'send')this.chat();
      else if(this.buttonType === 'stop')this.stop();
    },
    chat(){
      this.anwser = "";
      console.log(this.socket.readyState);
      if(!this.question){
        this.$message.warning("请输入问题");
        return;
      }
      //新增消息记录
      this.msgList.push({
        content:this.question,
        type:"user"
      })
      this.msgList.push({
        content:"...",
        type:"bot"
      })
      //滚动到最底部
      this.$refs.scrollbar.setScrollTop(10000);
      //按扭文本变为发送中
      this.buttonTitle = "发送中";
      this.buttonDisable = true;  
      this.buttonType = "send";
      //发送ws消息
      this.socket.send(this.question);
      //清空输入框
      this.question = "";
    },
    stop(){
      //发送ws消息
      if(!this.currentCompletionId){
        this.$message.warning("没有正在生成的对话");
        return;
      }
      let msg = "[gpt:msg:stop]"+"&split&"+this.currentCompletionId;
      this.socket.send(msg);
      //恢复按扭状态
      this.buttonTitle = "发送";
      this.buttonDisable = false;  
      this.buttonType = "send";
    },
    end(){
      if (this.socket) {
        this.socket.close();
      }
    },
    loadStorageMsgList(){
      let smsgList = this.$TOOL.data.get(this.getCurrUserId()+"chatgptMsgList");
      if(smsgList)this.msgList = smsgList;
    },
    getCurrUserId(){
      let userInfo = this.$TOOL.data.get("USER_INFO");
      if(!userInfo)return null;
      console.log(userInfo.id)
      return userInfo.id;
    },
    getCurrToken(){
      var token = this.$TOOL.data.get("TOKEN");
      return token;
    }
  },
  mounted() {
    //加载本地记录
    this.loadStorageMsgList();
    //创建websocket连接
    this.createConnect();
  }
}
</script>

<style scoped>
      .chat-container {
        margin: 0 auto;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        border: 1px #0000002f solid;
        padding: 20px;
        height: calc(100% - 100px);
      }
      .user-message {
        display: flex;
        align-items: center;
        background-color: #e2f0cb;
        border-radius: 5px;
        margin-bottom: 10px;
        font-size: 15px;
      }
      .bot-message {
        display: flex;
        align-items: center;
        background-color: #d1d8e0;
        border-radius: 5px;
        margin-bottom: 10px;
        font-size: 15px;
      }

      .avatar {
        width: 3em;
        height: 3em;
        margin-left: 10px;
        margin-top:10px;
        margin-bottom: 25px;
      }

      .input-container {
        margin-top:10px;
        display: flex;
        border: 1px #0000002f solid;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        border-radius: 5px;
        padding: 5px;
      }
      .input-container input {
        flex: 1;
        padding: 10px;
        border: none;
        border-radius: 5px;
      }
      .input-container button {
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        margin-left: 10px;
        cursor: pointer;
      }
    </style>